<template>
  <el-container direction="vertical">
    <el-header>
      <el-menu mode="horizontal" default-active="currentRoute.path" router>
        <el-menu-item
          index="/basicInfo"
          class="menu-item"
          :class="{ 'active': $route.path === '/basicInfo' }"
        >基础信息维护</el-menu-item>
        <el-menu-item
          index="/extendedInfo"
          class="menu-item"
          :class="{ 'active': $route.path === '/extendedInfo' }"
        >机构扩展信息</el-menu-item>
        <el-menu-item
          index="/serviceFacilities"
          class="menu-item"
          :class="{ 'active': $route.path === '/serviceFacilities' }"
        >服务项目和设施</el-menu-item>
        <el-menu-item
          index="/term"
          class="menu-item"
          :class="{ 'active': $route.path === '/term' }"
        >服务条款</el-menu-item>
        <el-menu-item
          index="/note"
          class="menu-item"
          :class="{ 'active': $route.path === '/note' }"
        >须知与注意事项</el-menu-item>
      </el-menu>
    </el-header>

    <el-main>
      <el-form ref="form" :model="form" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  机构编码
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-input v-model="form.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  机构名称
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  机构性质
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-select v-model="form.property" placeholder="请选择">
                <el-option
                  v-for="property in propertyType"
                  :key="property.id"
                  :label="property.name"
                  :value="property.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="机构电话">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构规模">
              <el-input v-model="form.scale"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  机构类型
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="type in typeList"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="机构地址">
              <el-cascader
                placeholder="请选择"
                v-model="form.currentAddress"
                :options="addressOptions"
                clearable
                filterable
                @change="handleAddressChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="详细地址">
              <el-input v-model="form.address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <template #label>
            <span>
              机构介绍
              <span style="color: red;">*</span>
            </span>
          </template>
          <el-input v-model="form.introduction" type="textarea" :rows="5" :cols="30"></el-input>
        </el-form-item>

        <el-row :gutter="24">
          <!-- 上传图片框1 -->
          <el-col :span="24">
            <el-form-item label="机构图标">
              <div style="display: flex; align-items: center;">
                <div>
                  <el-upload
                    action="api/employee/upload"
                    :on-success="handleAvatarSuccess"
                    :show-file-list="false"
                    v-model="form.mechanismSrc"
                    :limit="1"
                    list-type="picture"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <div style="margin-top: 10px;">
                      <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                    </div>
                  </el-upload>
                </div>
                <div>
                  <p
                    style="margin-left: 20px; margin-top: 10px;"
                  >建议上传200*200尺寸大小，图标格式为jpg、jpeg、png类型</p>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!-- 上传图片框2 -->
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  营业执照
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-upload
                action="api/employee/upload"
                :on-success="handleAvatarSuccess2"
                :show-file-list="false"
                v-model="form.licenseSrc"
                :limit="1"
                list-type="picture"
              >
                <img v-if="imageUrl2" :src="imageUrl2" class="avatar" />
                <div style="margin-top: 10px;">
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <!-- 上传图片框3 -->
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  税务登记证
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-upload
                action="api/employee/upload"
                :on-success="handleAvatarSuccess3"
                :show-file-list="false"
                v-model="form.taxationSrc"
                :limit="1"
                list-type="picture"
              >
                <img v-if="imageUrl3" :src="imageUrl3" class="avatar" />
                <div style="margin-top: 10px;">
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <!-- 上传图片框4 -->
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  消防许可证
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-upload
                action="api/employee/upload"
                :on-success="handleAvatarSuccess4"
                :show-file-list="false"
                v-model="form.protectionSrc"
                :limit="1"
                list-type="picture"
              >
                <img v-if="imageUrl4" :src="imageUrl4" class="avatar" />
                <div style="margin-top: 10px;">
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <!-- 上传图片框5 -->
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  卫生许可证
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-upload
                action="api/employee/upload"
                :on-success="handleAvatarSuccess5"
                :show-file-list="false"
                v-model="form.healthSrc"
                :limit="1"
                list-type="picture"
              >
                <img v-if="imageUrl5" :src="imageUrl5" class="avatar" />
                <div style="margin-top: 10px;">
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <!-- 上传图片框6 -->
          <el-col :span="8">
            <el-form-item>
              <template #label>
                <span>
                  医疗许可证
                  <span style="color: red;">*</span>
                </span>
              </template>
              <el-upload
                action="api/employee/upload"
                :on-success="handleAvatarSuccess6"
                :show-file-list="false"
                v-model="form.medicalSrc"
                :limit="1"
                list-type="picture"
              >
                <img v-if="imageUrl6" :src="imageUrl6" class="avatar" />
                <div style="margin-top: 10px;">
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="header-buttons">
        <!-- 其他内容 -->
        <el-button type="primary" @click="update">编辑</el-button>
      </div>
    </el-main>
  </el-container>
</template>
  
  <script>
export default {
  data() {
    return {
  
      imageUrl: "",
      imageUrl2: "",
      imageUrl3: "",
      imageUrl4: "",
      imageUrl5: "",
      imageUrl6: "",
      form: {
        code: "",
        name: "",
        property: "",
        phone: "",
        scale: "",
        type: "",
        address: "",
        detailed_address: "",
        introduction: "",
        mechanismSrc: "",
        licenseSrc: "",
        taxationSrc: "",
        protectionSrc: "",
        healthSrc: "",
        medicalSrc: "",
        currentAddress: []
      },

      propertyType: [
        { id: "1", name: "公立" },
        { id: "2", name: "私立" },
        { id: "3", name: "集团" },
        { id: "4", name: "其他" }
      ],
      typeList: [
        { id: "1", name: "养老院" },
        { id: "2", name: "护理院" },
        { id: "3", name: "疗养院" }
      ],
      addressOptions: [
        {
          value: "省份ID",
          label: "省份名称",
          children: [
            {
              value: "城市ID",
              label: "城市名称",
              children: [
                {
                  value: "县区ID",
                  label: "县区名称"
                }
                // 更多县区...
              ]
            }
            // 更多城市...
          ]
        }
        // 更多省份...
      ]
    };
  },
  methods: {
    update() {
     // 验证必填项
  if (
    !this.form.code ||
    !this.form.name ||
    !this.form.property ||
    !this.form.type ||
    !this.form.introduction ||
    !this.imageUrl2 ||
    !this.imageUrl3 ||
    !this.imageUrl4 ||
    !this.imageUrl5 ||
    !this.imageUrl6
  ) {
    this.$message.error("请填写所有必填项！");
    return;
  }
      let currentAddress = "";
      let optionLevel1 = this.addressOptions.find(
        option => option.value === this.form.currentAddress[0]
      );
      if (optionLevel1) {
        currentAddress += optionLevel1.label;
        if (optionLevel1.children) {
          let optionLevel2 = optionLevel1.children.find(
            option => option.value === this.form.currentAddress[1]
          );
          if (optionLevel2) {
            currentAddress += ", " + optionLevel2.label;
            if (optionLevel2.children) {
              let optionLevel3 = optionLevel2.children.find(
                option => option.value === this.form.currentAddress[2]
              );
              if (optionLevel3) {
                currentAddress += ", " + optionLevel3.label;
              }
            }
          }
        }
      }
      this.form.currentAddress = currentAddress;
      //添加图片
      this.form.mechanismSrc = this.imageUrl;
      this.form.licenseSrc = this.imageUrl2;
      this.form.taxationSrc = this.imageUrl3;
      this.form.protectionSrc = this.imageUrl4;
      this.form.healthSrc = this.imageUrl5;
      this.form.medicalSrc = this.imageUrl6;

      console.log("机构信息: ", this.form);
      let mechanism = this.form;
      this.$axios.post("api/mechanism/updateMechanism", mechanism).then(res => {
        if (res.data.code == 200) {
          this.$message.success("提交成功!");
          this.queryById();
          // this.$router.push({ path: "/basicInfo" });
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },

    handleAddressChange(value, selectedData) {
      this.form.currentAddress = value;
    },
    handleAvatarSuccess(res, file) {
      console.log(res.data);
      this.imageUrl = res.data;
    },
    handleAvatarSuccess2(res, file) {
      console.log(res.data);
      this.imageUrl2 = res.data;
    },
    handleAvatarSuccess3(res, file) {
      console.log(res.data);
      this.imageUrl3 = res.data;
    },
    handleAvatarSuccess4(res, file) {
      console.log(res.data);
      this.imageUrl4 = res.data;
    },
    handleAvatarSuccess5(res, file) {
      console.log(res.data);
      this.imageUrl5 = res.data;
    },
    handleAvatarSuccess6(res, file) {
      console.log(res.data);
      this.imageUrl6 = res.data;
    },
    getLocations() {
      this.$axios.get("api/location/queryLocation").then(response => {
        function removeChildrenForCounties(options) {
          for (const option of options) {
            if (option.children) {
              // 如果children是一个空数组，删除它
              if (option.children.length === 0) {
                delete option.children;
              }
              // 否则，递归处理下一级的选项
              else {
                removeChildrenForCounties(option.children);
              }
            }
          }
        }

        this.addressOptions = response.data.data;
        removeChildrenForCounties(this.addressOptions);
        this.queryById();
      });
    },
    queryById() {
      this.$axios.get("api/mechanism/queryById/" + "1").then(res => {
        if (res.data.code == 200) {
          console.log(res.data);
          const originalForm = res.data.data;
          // 获取图片
          this.imageUrl = originalForm.mechanismSrc;
          this.imageUrl2 = originalForm.licenseSrc;
          this.imageUrl3 = originalForm.taxationSrc;
          this.imageUrl4 = originalForm.protectionSrc;
          this.imageUrl5 = originalForm.healthSrc;
          this.imageUrl6 = originalForm.medicalSrc;

          // 数字代码转为下拉列表的值
          const property = this.propertyType.find(
            item => item.id === String(originalForm.property)
          );
          const type = this.typeList.find(
            item => item.id === String(originalForm.type)
          );
          originalForm.property = property ? property.id : "";
          originalForm.type = type ? type.id : "";
          console.log(originalForm.currentAddress);
          // 如果现住地址是字符串,转为数组
          // 如果currentAddress是字符串，转换为数组
          let labels = originalForm.currentAddress.split(", ");

          console.log(labels);

          //然后使用findValueByLabel函数获取对应的值数组

          let values = this.findValueByLabel(this.addressOptions, labels);

          //最后将值数组赋值给form.currentAddress
          this.form = originalForm;
          this.form.currentAddress = values;

          console.log(this.form.currentAddress);
        }
      });
    },
    findValueByLabel(options, labels, index = 0) {
      const valuePath = [];

      function findInChildren(children, label) {
        let found = false;
        for (let child of children) {
          if (child.label === label) {
            valuePath.push(child.value);
            found = true;
            break;
          }
        }

        return found;
      }

      const currentLabel = labels[index];
      if (options.some(option => findInChildren([option], currentLabel))) {
        if (index < labels.length - 1) {
          let nextOptions = options.find(
            option => option.label === currentLabel
          ).children;
          let nextValues = this.findValueByLabel(
            nextOptions,
            labels,
            index + 1
          );
          if (nextValues) {
            valuePath.push(...nextValues);
          }
        }
        return valuePath;
      }
    }
  },
  created() {
    this.getLocations();
    this.queryById();
  }
};
</script>
<style>
.menu-item.active {
  background-color: #3e9ff5; /* 选中菜单项的背景色 */
  color: #333; /* 选中菜单项的文字颜色 */
}
.header-buttons {
  display: flex;
  justify-content: flex-end;
}
.avatar {
  width: 150px; /* 调整为你需要的宽度 */
  height: 150px; /* 调整为你需要的高度 */
  object-fit: cover; /* 这条语句会使图片以 "cover" 模式显示，保持图片的本身比例长宽比，裁剪超出部分 */
}
</style>